﻿#include "WidgetReadCfg.h"
#include <QFormLayout>
#include <QLabel>
#include <QInputDialog>

#pragma execution_character_set("utf-8")
WidgetReadCfg::WidgetReadCfg(QWidget *parent)
    : QWidget{parent}
{

    setupUi();
    initConnect();
}

void WidgetReadCfg::setRequestCfg(const QMap<QString, PLCRequestData>& data)
{
    QStringList lstKey = data.keys();
    std::for_each(lstKey.begin(), lstKey.end(), [&](QString key){
        WidgetReadRequest* wgt = new WidgetReadRequest();
        wgt->setRequestData(data.value(key));
        tabwgt->addTab(wgt, key);
    });
}

QMap<QString, PLCRequestData> WidgetReadCfg::getRequestCfg()
{
    QMap<QString, PLCRequestData> mapReadCfg;
    int count = tabwgt->count();
    for(int i = 0; i < count; ++i){
        QString name = tabwgt->tabText(i);
        WidgetReadRequest* wgt = static_cast<WidgetReadRequest*>(tabwgt->currentWidget());
        mapReadCfg.insert(name, wgt->getRequestData());
    }
    return mapReadCfg;
}

void WidgetReadCfg::setupUi()
{
    pbtnAdd = new QPushButton("添加");
    pbtnRemove = new QPushButton("删除");
    pbtnRemoveAll = new QPushButton("删除全部");
    tabwgt = new QTabWidget();

    QGridLayout* gLayout01 = new QGridLayout();
    gLayout01->addWidget(pbtnAdd, 0, 0);
    gLayout01->addWidget(pbtnRemove, 0, 1);
    gLayout01->addWidget(pbtnRemoveAll, 0, 2);

    QVBoxLayout* vLayoutCtrl = new QVBoxLayout();
    this->setLayout(vLayoutCtrl);
    vLayoutCtrl->addLayout(gLayout01);
    vLayoutCtrl->addWidget(tabwgt);
    vLayoutCtrl->addStretch();
}

void WidgetReadCfg::initConnect()
{
    connect(pbtnAdd, &QPushButton::clicked, this, [&](){
        QString name = getTxt();
        tabwgt->addTab(new WidgetReadRequest(), name);
    });
    connect(pbtnRemove, &QPushButton::clicked, this, [&](){
        tabwgt->removeTab(tabwgt->currentIndex());
    });
    connect(pbtnRemoveAll, &QPushButton::clicked, this, [&](){
        int count = tabwgt->count();
        for(int i = 0; i < count; ++i){
            tabwgt->removeTab(0);
        }
    });
}
QString WidgetReadCfg::getTxt()
{
    return QInputDialog::getText(this, "输入读取配置名称", "名称", QLineEdit::Normal, "配置1");;
}
